package org.spider.api.utils.http;

import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;

import java.util.Map;

public class HttpResponse implements SpiderResponse {

    private Response response;

    private int statusCode;

    private String urlLink;

    private String htmlValue;

    private String titleName;

    public HttpResponse(Response response){
        super();
        this.response = response;
        this.statusCode = response.statusCode();
        this.urlLink = response.url().toExternalForm();
    }

    @Override
    public int getStatusCode(){
        return statusCode;
    }
    // 单例模式，一次解析，减少时间
    @Override
    public String getTitle() {
        if (titleName == null) {
            synchronized (this){
                titleName = Jsoup.parse(getHtml()).title();
            }
        }
        return titleName;
    }

    @Override
    public String getHtml(){
        if(htmlValue == null){
            synchronized (this){
                htmlValue = response.body();
            }
        }
        return htmlValue;
    }
    @Override
    public Map<String,String> getCookies(){
        return response.cookies();
    }

    @Override
    public Map<String,String> getHeaders(){
        return response.headers();
    }


    @Override
    public String getContentType(){
        return response.contentType();
    }

    @Override
    public void setCharset(String charset) {
        this.response.charset(charset);
    }

    @Override
    public String getUrl() {
        return urlLink;
    }
}
